package com.ddsso.auth.web.filter;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;

import com.ddsso.auth.web.session.MutableHttpServletRequest;
import com.ddsso.auth.web.util.AuthDesCoderUtil;

import javax.servlet.*;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;

/**
 * @author zdd
 * @package com.ddsso.user.web.filter
 * @Time Created by zdd on 2016/11/1.
 * @description To-do
 */
public class ShareSessionFilter  extends BaseFilter{
    private static Logger logger = Logger.getLogger(ShareSessionFilter.class);

    private static String SESSION_SHARE_SIGN="SHARE_JSESSIONID";
    private String ihomeHeaderToken = "ihome-token";
    private String paramSessionToken="token";
    private String paramSessionSidToken="sidToken";


    /**
     * @description 对SHARE_SESSIONID进行初始化
     * @param req
     * @param resp
     * @param filterChain
     * @throws IOException
     * @throws ServletException
     */
    protected void doFilterInternal(HttpServletRequest req, HttpServletResponse resp, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        String cookidShareSessionId=getCurrentCookieShareSession(request.getCookies());

        String shareSessionToken=StringUtils.isNotBlank(req.getParameter(paramSessionToken))?StringUtils.trim(req.getParameter(paramSessionToken)):"";

        /**
         * @description 用于地址密文token处理，如果是直接跳转的化，将token=XXX转换为sidToken=“token=XX”的形式，为了不影响内部变量的处理，此拦截器尽量配置在分布式拦截器的前面
         */
        if(!StringUtils.isNotBlank(shareSessionToken)){
            if(StringUtils.isNotBlank(req.getParameter(paramSessionSidToken))){
                shareSessionToken=URLDecoder.decode(StringUtils.trim(req.getParameter(paramSessionSidToken)), "UTF-8");
                shareSessionToken=StringUtils.remove(shareSessionToken,paramSessionToken+"=");
                logger.info(shareSessionToken);
            }
        }
        final String currentHeaderShareSessionId=request.getHeader(ihomeHeaderToken);
        MutableHttpServletRequest mutableRequest = new MutableHttpServletRequest(request);

        if(StringUtils.isNotBlank(shareSessionToken)){
            Cookie cookieName = new Cookie(SESSION_SHARE_SIGN, URLEncoder.encode(shareSessionToken,"UTF-8"));
            //cookie  每次都带来, 设置路径
            cookieName.setPath("/");
            //0:关闭浏览器  销毁cookie. 0:立即消失.  >0 存活时间,秒
            cookieName.setMaxAge(-1);
            response.addCookie(cookieName);
            request.setAttribute(paramSessionToken, shareSessionToken);
            mutableRequest.putHeader(ihomeHeaderToken, shareSessionToken);
        }else if(StringUtils.isNotBlank(currentHeaderShareSessionId)){
            Cookie cookieName = new Cookie(SESSION_SHARE_SIGN, URLEncoder.encode(currentHeaderShareSessionId,"UTF-8"));
            //cookie  每次都带来, 设置路径
            cookieName.setPath("/");
            //0:关闭浏览器  销毁cookie. 0:立即消失.  >0 存活时间,秒
            cookieName.setMaxAge(-1);
            response.addCookie(cookieName);
            request.setAttribute(paramSessionToken,currentHeaderShareSessionId);
            mutableRequest.putHeader(ihomeHeaderToken, currentHeaderShareSessionId);
        }else if(StringUtils.isNotBlank(cookidShareSessionId)){
           // cookidShareSessionId=URLDecoder.decode(cookidShareSessionId, "UTF-8");
            request.setAttribute(paramSessionToken,cookidShareSessionId);
            mutableRequest.putHeader(ihomeHeaderToken, cookidShareSessionId);
        }

        filterChain.doFilter(mutableRequest,response);
    }



    @Override
    public void destroy() {
    }

    private String getCurrentCookieShareSession(Cookie[] cookies) {
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                String name = cookie.getName();
                if (SESSION_SHARE_SIGN.equals(name)) {
                    if(cookie.getValue()!=null&&StringUtils.isNotBlank(cookie.getValue())){
                        try{
                            return URLDecoder.decode(cookie.getValue(),"UTF-8");
                        }catch (Exception e){
                            logger.info("取cookie出错..........");
                            return "";
                        }
                    }
                }
            }
        }
        return null;
    }


}
